import configparser
import json
import os
import requests
# can not directly use：import init_api_attribute because of xxx
from api.common import init_api_attribute
from PIL import Image
import pytesseract
import tempfile


def send_api_request(method, parameters, path):
    # 这是当前文件目录下的相对路劲，不能写错
    # file = '../api_info.ini'
    # config = configparser.ConfigParser()
    # if os.path.exists(file):
    #     config.read(file, encoding="utf-8")
    #     selections = config.sections()
    #     print('selections是：')
    #     print(selections)
    #
    #     env = init_api_attribute.init_config('prod')
    #
    #     if method == 'post':
    #         response = requests.post(env + path, json=parameters)
    #     else:
    #         response = requests.get()
    #
    #     print(response)
    # else:
    #     print('file not exist')
    #     return None

    env = init_api_attribute.init_config('pro')
    if env is None:
        return '测试环境为空或错误'
        raise ValueError('测试环境为空或错误')
    if method is None:
        return '请求方式为空或错误'
        raise ValueError('请求方式为空或错误')
    if method is None:
        return '参数为空'
        raise ValueError('参数为空')

    if method == 'GET':
        send_get(parameters, path, env)
    if method == 'POST':
        send_post(parameters, path, env)


def send_get(parameters, path, env):
    url = env + path
    params = parameters.replace(',', '&')
    # url_request = url + params
    url_get = url + '?' + params
    url_get = url_get.replace('\'', '')

    if 'captcha' in url_get:
        return get_captcha_code(url_get)

    response = requests.get(url_get)
    response.encoding = 'utf-8'
    if is_json(str(response)):
        data = response.json()
        print('接口返回：')
        print(data)
        return data
    return response


def send_post(parameters, path, env):
    url = env + path

    url = url.replace('\'', '')

    response = requests.post(url, parameters)

    response.encoding = 'utf-8'
    if is_json(str(response)):
        data = response.json()
        print('接口返回：')
        print(data)
        return data
    print('接口返回：')
    return response


def is_json(data):
    try:
        json.loads(data)
    except ValueError:
        return False
    return True


def get_captcha_code(captcha_url):
    # tempfile.tempdir = 'C:\\Users\\13096\\Documents\\workspace\\vprotect-test-project'
    pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'  # Windows路径
    # pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'  # Linux/macOS路径
    # 发送请求获取验证码图片

    response = requests.get(captcha_url)
    # 检查请求是否成功
    if response.status_code == 200:
        # 将响应内容作为图片保存
        with open('captcha.jpg', 'wb') as f:
            f.write(response.content)
        # 使用Pillow打开并处理图形验证码
        # with Image.open('captcha.png') as img:
        #     # 这里可以添加处理图像的代码，例如识别验证码中的文字
        #     # 例如，可以将图像转换为灰度图像
        #     img = img.convert('L')
        #     # 保存处理后的图像
        #     img.save('captcha_processed.png')
        #
        #     code = pytesseract.image_to_data(img)
        #     return code
        image = Image.open('captcha.jpg')
        image = image.convert('L')
        image = image.resize(2*image.width, 2*image.height)
        # code = pytesseract.image_to_string(image, config='--psm 6')
        code = pytesseract.image_to_string(image)

        print('识别结果：~~~~~~~~~~~~~~~~~~~~~~')
        print(code)
    else:
        print('Failed to fetch captcha')
        return 'Failed to fetch captcha'


def recognize_captcha(captcha_url, save_path):
    response = requests.get(captcha_url)
    with open(save_path, 'wb') as f:
        f.write(response.content)

    image = Image.open(save_path)

    # 二值化处理图片
    threshold = 127
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    image = image.point(table, '1')
